package com.cpdmali.api.helper;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Properties;

import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cpdmali.api.Exception.BadParameterException;

public class CpdMaliApiWSConnector {
	
	private static final Logger log = LoggerFactory.getLogger(CpdMaliApiWSConnector.class);
	
	/** Configurator. **/
	static Properties CFG;

	private final static String SEPARATOR = "/";

	private final static String HOST_WS_SERVER = CFG.getProperty(ConstanteProperties.HOST_WS_SERVER);

	private final static String NAME_WS_SERVER = CFG.getProperty(ConstanteProperties.NAME_WS_SERVER);

	private final static String ROOT_WS_SERVER = HOST_WS_SERVER + SEPARATOR + NAME_WS_SERVER;

	private static final String X_CPD_MALI_TRANSACTION_FORMAT = "CPDMALI-WS-CONNECTOR-{0,date,yyyyMMddHHmmssS}";
	
	public CpdMaliApiWSConnector(String propertiesFile){
		try {
			CFG = PropertiesInit.initApplicationProperties(propertiesFile);
		} catch (BadParameterException e) {
			log.debug("Erreur lors du chargement du fichier", e);
		}
	}
	
	/**
	 * 
	 * @param urlToGet
	 * @param contentType
	 * @return
	 * @throws IOException
	 * @throws URISyntaxException
	 * @throws HttpException
	 */
	public static HttpResponse getResponseFromCrewIntranetWS(String urlToGet, String contentType) {
		HttpResponse response = null;
		try {
			HttpClient httpClient = CpdMaliApiWSConnector.getHttpClient();
			HttpGet getRequeste = new HttpGet(urlToGet);
			String transactionID = CpdMaliApiWSConnector.getTransactionId();
			getRequeste.addHeader(HeaderName.TRANSACTION_ID, transactionID);
			getRequeste.addHeader(HeaderName.CONTENT_TYPE, contentType);

			response = httpClient.execute(getRequeste);
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return response;
	}

	public static HttpResponse postResponseFromCrewIntranetWS(final String urlToGet, final String contentBody, final String contentType, 
			final String accept) {
		
		HttpResponse response = null;
		try {
			HttpClient httpClient = CpdMaliApiWSConnector.getHttpClient();
			HttpPost postRequeste = new HttpPost(urlToGet);
			String transactionID = CpdMaliApiWSConnector.getTransactionId();
			postRequeste.addHeader(HeaderName.TRANSACTION_ID, transactionID);
			if (!StringTools.isEmpty(contentType)) {
				postRequeste.addHeader(HeaderName.CONTENT_TYPE, contentType);
			}
			if (!StringTools.isEmpty(accept)) {
				postRequeste.addHeader(HeaderName.ACCEPT, accept);
			}
			if (!StringTools.isEmpty(contentBody)) {
				StringEntity entity = new StringEntity(contentBody);
				postRequeste.setEntity(entity);
			}
			// execute query
			response = httpClient.execute(postRequeste);

		} catch (UnsupportedEncodingException e) {
			log.debug("Erreur lors de la connexion au WS", e);
			e.printStackTrace();
		} catch (IOException e) {
			log.debug("Erreur lors de la connexion au WS", e);
		}
		
		return response;
	}

	/**
	 * 
	 * @return
	 */
	public static DefaultHttpClient getHttpClient() {
		int connectionTimeout = Integer.parseInt(CFG
				.getProperty(ConstanteProperties.CONNECTION_TIMEOUT));
		int soTimeout = Integer.parseInt(CFG
				.getProperty(ConstanteProperties.SO_TIMEOUT));

		HttpParams httpParams = new BasicHttpParams();
		httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
		httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
				connectionTimeout);
		return new DefaultHttpClient(httpParams);
	}

	public static String getTransactionId() {
		return MessageFormat.format(X_CPD_MALI_TRANSACTION_FORMAT,
				new Date());
	}
	
}
